package dao;

import classes.Tip;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class TipDAO {
	@SuppressWarnings("unused")
	private final Connection c;
	private final PreparedStatement qInsert, qSelectAll, qDelete, qSelectTip;
	
	public TipDAO(Connection c) throws Exception {
		this.c = c;
		qInsert= c.prepareStatement("INSERT INTO Tip(idTip, naziv) VALUES(null, ?)");
		qSelectAll = c.prepareStatement("SELECT * FROM Tip");
		qDelete = c.prepareStatement("DELETE FROM Tip WHERE idTip=?");
		qSelectTip = c.prepareStatement("SELECT * FROM Tip WHERE idTip = ?");
	}

	public int insertTip(Tip t) throws Exception {
		if (t==null)
			throw new Exception("Nije moguce dodati nepostojeci tip!");
		qInsert.setString(1, t.getNaziv());
		try{
			int r= qInsert.executeUpdate();
			return r;
		}
		catch(Exception ex){
			throw new Exception("Greska kod dodavanja marketa!");
		}
	}
	
	public Tip selectTip(int id) throws Exception{
		qSelectTip.setInt(1, id);
		ResultSet rs = qSelectTip.executeQuery();
		if(rs.next()==false)
			throw new Exception("Vratio null");
		Tip t = new Tip();
		t.setIdTip(rs.getInt("idTip"));
		t.setNaziv(rs.getString("naziv"));
		return t;
	}
	
	
	public List<Tip> selectSviTipovi() throws Exception{
		ResultSet rs = qSelectAll.executeQuery();
		List<Tip> tipovi = new ArrayList<Tip>();
		while (rs.next()){
			Tip t= new Tip();
			t.setIdTip(rs.getInt("idTip"));
			t.setNaziv(rs.getString("naziv"));
			tipovi.add(t);
		}
		return tipovi;
	}

	public int deleteTip(int id) throws Exception {
		qDelete.setInt(1, id);
		return qDelete.executeUpdate();
	}


}
